<template>
  <div class="tab-nav">
    <div class="tab-nav-wrapper">
      <!-- 左侧滚动按钮 -->
      <div 
        v-if="canScrollLeft" 
        class="scroll-button scroll-left" 
        @click="scrollToLeft"
      >
        <n-icon size="16">
          <Icons name="chevron-back-outline" />
        </n-icon>
      </div>
      
      <!-- Tab列表容器 -->
      <div class="tab-list-container" ref="tabContainerRef">
        <div class="tab-list" ref="tabListRef">
          <div
            v-for="tab in tabs"
            :key="tab.path"
            ref="tabItemRefs"
            class="tab-item"
            :class="{ 'tab-item--active': activeTab === tab.path }"
            @click="handleTabClick(tab.path)"
            @contextmenu.prevent="handleRightClick($event, tab)"
          >
            <span class="tab-title">{{ getTabTitle(tab.title) }}</span>
            <n-icon
              v-if="tab.closable"
              class="tab-close"
              size="14"
              @click.stop="handleTabClose(tab.path)"
            >
              <Icons name="close-outline" />
            </n-icon>
          </div>
        </div>
      </div>
      
      <!-- 右侧滚动按钮 -->
      <div 
        v-if="canScrollRight" 
        class="scroll-button scroll-right" 
        @click="scrollToRight"
      >
        <n-icon size="16">
          <Icons name="chevron-forward-outline" />
        </n-icon>
      </div>
    </div>
    
    <!-- 右键菜单 -->
    <n-dropdown
      :show="showDropdown"
      :x="dropdownX"
      :y="dropdownY"
      :options="dropdownOptions"
      @select="handleDropdownSelect"
      @clickoutside="showDropdown = false"
      placement="bottom-start"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/store'
import { NIcon, NDropdown } from 'naive-ui'
import Icons from './Icons.vue'
import type { TabItem } from '@/store'

const router = useRouter()
const { t } = useI18n({ useScope: 'global' })
const appStore = useAppStore()

const tabListRef = ref<HTMLElement>()
const tabContainerRef = ref<HTMLElement>()
const tabItemRefs = ref<HTMLElement[]>([])
const showDropdown = ref(false)
const dropdownX = ref(0)
const dropdownY = ref(0)
const rightClickedTab = ref<TabItem | null>(null)

// 滚动相关状态
const canScrollLeft = ref(false)
const canScrollRight = ref(false)
const scrollLeft = ref(0)

const tabs = computed(() => appStore.tabs)
const activeTab = computed(() => appStore.activeTab)

// 获取标签页标题的国际化文本
const getTabTitle = (titleKey: string) => {
  if (titleKey.startsWith('menu.')) {
    return t(titleKey)
  }
  return t(`menu.${titleKey}`)
}

// 更新滚动状态
const updateScrollState = () => {
  if (!tabContainerRef.value) return
  
  const container = tabContainerRef.value
  const scrollWidth = container.scrollWidth
  const clientWidth = container.clientWidth
  const scrollLeft = container.scrollLeft
  
  canScrollLeft.value = scrollLeft > 0
  canScrollRight.value = scrollLeft < scrollWidth - clientWidth
}

// 滚动到左侧
const scrollToLeft = () => {
  if (!tabContainerRef.value) return
  
  const container = tabContainerRef.value
  const scrollAmount = 200 // 每次滚动200px
  container.scrollTo({
    left: Math.max(0, container.scrollLeft - scrollAmount),
    behavior: 'smooth'
  })
}

// 滚动到右侧
const scrollToRight = () => {
  if (!tabContainerRef.value) return
  
  const container = tabContainerRef.value
  const scrollAmount = 200 // 每次滚动200px
  container.scrollTo({
    left: container.scrollLeft + scrollAmount,
    behavior: 'smooth'
  })
}

// 滚动到指定Tab
const scrollToTab = (tabPath: string) => {
  if (!tabContainerRef.value) return
  
  const tabIndex = tabs.value.findIndex(tab => tab.path === tabPath)
  if (tabIndex === -1 || !tabItemRefs.value[tabIndex]) return
  
  const container = tabContainerRef.value
  const tabElement = tabItemRefs.value[tabIndex]
  const containerRect = container.getBoundingClientRect()
  const tabRect = tabElement.getBoundingClientRect()
  
  // 计算Tab相对于容器的位置
  const tabLeft = tabRect.left - containerRect.left + container.scrollLeft
  const tabRight = tabLeft + tabRect.width
  const containerWidth = container.clientWidth
  
  let targetScrollLeft = container.scrollLeft
  
  // 如果Tab在可视区域左侧
  if (tabLeft < container.scrollLeft) {
    targetScrollLeft = tabLeft - 20 // 留20px边距
  }
  // 如果Tab在可视区域右侧
  else if (tabRight > container.scrollLeft + containerWidth) {
    targetScrollLeft = tabRight - containerWidth + 20 // 留20px边距
  }
  
  if (targetScrollLeft !== container.scrollLeft) {
    container.scrollTo({
      left: Math.max(0, targetScrollLeft),
      behavior: 'smooth'
    })
  }
}

// 标签页点击处理
const handleTabClick = (path: string) => {
  appStore.setActiveTab(path)
  router.push(path)
  // 自动滚动到选中的Tab
  nextTick(() => {
    scrollToTab(path)
  })
}

// 标签页关闭处理
const handleTabClose = (path: string) => {
  const index = tabs.value.findIndex(tab => tab.path === path)
  appStore.removeTab(path)
  
  // 如果关闭的是当前标签页，需要跳转到新的活跃标签页
  if (activeTab.value && activeTab.value !== path) {
    router.push(activeTab.value)
  }
}

// 右键菜单处理
const handleRightClick = (event: MouseEvent, tab: TabItem) => {
  rightClickedTab.value = tab
  dropdownX.value = event.clientX
  dropdownY.value = event.clientY
  showDropdown.value = true
}

// 右键菜单选项
const dropdownOptions = computed(() => {
  const options = []
  
  if (rightClickedTab.value?.closable) {
    options.push({
      label: '关闭',
      key: 'close'
    })
  }
  
  options.push(
    {
      label: '关闭其他',
      key: 'closeOthers'
    },
    {
      label: '关闭所有',
      key: 'closeAll'
    }
  )
  
  return options
})

// 右键菜单选择处理
const handleDropdownSelect = (key: string) => {
  if (!rightClickedTab.value) return
  
  const tabPath = rightClickedTab.value.path
  
  switch (key) {
    case 'close':
      handleTabClose(tabPath)
      break
    case 'closeOthers':
      appStore.removeOtherTabs(tabPath)
      if (activeTab.value !== tabPath) {
        router.push(tabPath)
      }
      break
    case 'closeAll':
      appStore.removeAllTabs()
      if (activeTab.value) {
        router.push(activeTab.value)
      }
      break
  }
  
  showDropdown.value = false
  rightClickedTab.value = null
}

// 监听Tab变化，自动滚动到活跃Tab
watch(() => activeTab.value, (newActiveTab) => {
  if (newActiveTab) {
    nextTick(() => {
      scrollToTab(newActiveTab)
      updateScrollState()
    })
  }
})

// 监听Tab数量变化，更新滚动状态
watch(() => tabs.value.length, () => {
  nextTick(() => {
    updateScrollState()
  })
})

// 监听路由变化，自动添加标签页
router.afterEach((to) => {
  if (to.meta?.title && !to.meta?.hideInTab) {
    appStore.addTab(to)
  }
})

// 滚动事件监听
const handleScroll = () => {
  updateScrollState()
}

// 窗口大小变化监听
const handleResize = () => {
  updateScrollState()
}

// 组件挂载时的初始化
onMounted(() => {
  const currentRoute = router.currentRoute.value
  if (currentRoute.meta?.title) {
    appStore.addTab(currentRoute)
  }
  
  // 添加滚动监听
  if (tabContainerRef.value) {
    tabContainerRef.value.addEventListener('scroll', handleScroll)
  }
  
  // 添加窗口大小监听
  window.addEventListener('resize', handleResize)
  
  // 初始化滚动状态
  nextTick(() => {
    updateScrollState()
    if (activeTab.value) {
      scrollToTab(activeTab.value)
    }
  })
})

onBeforeUnmount(() => {
  // 清理监听器
  if (tabContainerRef.value) {
    tabContainerRef.value.removeEventListener('scroll', handleScroll)
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.tab-nav {
  height: 40px;
  background-color: transparent;
  border-bottom: none;
  overflow: hidden;
  width: 100%;
}

.tab-nav-wrapper {
  display: flex;
  align-items: center;
  height: 100%;
  width: 100%;
}

.tab-list-container {
  flex: 1;
  height: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  position: relative;
}

.tab-list-container::-webkit-scrollbar {
  height: 0px;
  background: transparent;
}

.tab-list {
  height: 100%;
  display: flex;
  align-items: center;
  white-space: nowrap;
  padding: 0;
  margin: 0;
  min-width: min-content;
}

.scroll-button {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: var(--bg-color-secondary);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  margin: 0 4px;
  color: var(--text-color);
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.scroll-button:hover {
  background-color: var(--border-color);
  color: var(--text-color);
}

.scroll-left {
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.scroll-right {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

[data-theme="dark"] .scroll-left {
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
}

[data-theme="dark"] .scroll-right {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.3);
}

.tab-item {
  height: 32px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
  border: 1px solid transparent;
  border-radius: 4px;
  margin: 4px 2px;
  background-color: var(--bg-color-secondary);
  color: var(--text-color-secondary);
  transition: all 0.2s ease;
  user-select: none;
  flex-shrink: 0;
}

.tab-item:hover {
  background-color: var(--border-color);
  color: var(--text-color);
}

.tab-item--active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.tab-item--active:hover {
  background-color: var(--primary-color-hover);
}

.tab-title {
  font-size: 13px;
  margin-right: 6px;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tab-close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  border-radius: 2px;
  opacity: 0.7;
  transition: all 0.2s ease;
}

.tab-close:hover {
  opacity: 1;
  background-color: rgba(255, 255, 255, 0.2);
}

.tab-item--active .tab-close:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tab-nav {
    height: 36px;
  }
  
  .scroll-button {
    width: 28px;
    height: 28px;
    margin: 0 2px;
  }
  
  .tab-item {
    height: 28px;
    padding: 0 8px;
    margin: 4px 1px;
  }
  
  .tab-title {
    font-size: 12px;
    margin-right: 4px;
    max-width: 80px;
  }
  
  .tab-close {
    width: 14px;
    height: 14px;
  }
}
</style>
